/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Control;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.XMLReaderFactory;

public class SourceValidateSchema {
    public boolean validateSchema(String schema, String xml){
        boolean OK = false;
        try {
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            File schemaFile = new File(schema);
            Schema xsdSchema = sf.newSchema(schemaFile);
            Validator validator = xsdSchema.newValidator();
            SAXSource source = new SAXSource(new NamespaceFilter(XMLReaderFactory.createXMLReader()),
                    new InputSource(new FileInputStream(xml)));
            validator.validate(source, null);
                    OK=true;
        } catch (IOException ex) {
            Logger.getLogger(SourceValidateSchema.class.getName()).log(Level.SEVERE, null, ex);
            OK=false;
        }  catch (SAXException ex) {
            Logger.getLogger(SourceValidateSchema.class.getName()).log(Level.SEVERE, null, ex);
            OK=false;
        }
        return OK;
       }
//    public static void main(String []args){
//            SourceValidateSchema s = new SourceValidateSchema();
//            System.out.println("Result:"+s.validateSchema("src/java/Resources/Register.xsd","C:/Users/MrBot/Documents/NetBeansProjects/FlowerShop/build/web/xml/Register.xml"));
//    }
}
class NamespaceFilter extends XMLFilterImpl {
    String requireNamespace = "http://xml.netbeans.org/schema/Register";
    private String requiredNamespace;
    public NamespaceFilter(XMLReader parent){
        super(parent);
    }
    @Override
    public void startElement (String arg0, String arg1, String arg2, Attributes arg3){
        try {
            if (arg0 != requiredNamespace) {
                arg0 = requiredNamespace;
            }
            super.startElement(arg0, arg1, arg2, arg3);
        } catch (SAXException ex) {
            Logger.getLogger(NamespaceFilter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}























